//
//  CDSoftwareViewController.m
//  CollectToDesktop
//
//  Created by 王启颖 on 2020/10/16.
//  Copyright © 2020 godbe. All rights reserved.
//

#import "CDSoftwareViewController.h"
#import "CDSoftwareCell.h"

@interface CDSoftwareViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *collectionFlow;
@property (strong, nonatomic) NSMutableArray *dataArr;
@property (weak, nonatomic) IBOutlet UITextField *searchTF;

@end

@implementation CDSoftwareViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"选择软件";
    
    _collectionFlow.minimumInteritemSpacing = 15;
//    _collectionFlow.minimumLineSpacing = 15;
    _collectionFlow.sectionInset = UIEdgeInsetsMake(28, 10, 0, 10);
    
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.scrollsToTop = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [_collectionView registerNib:[UINib nibWithNibName:@"CDSoftwareCell" bundle:nil] forCellWithReuseIdentifier:@"kCDSoftwareCellID"];
    
    [self getDate];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"返 回(2)"] forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0, 0, 60, 40)];
    button.contentEdgeInsets = UIEdgeInsetsMake(0, -20,0, 0);
    [button addTarget:self action:@selector(navigationItemBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem =  item;
}

-(void)navigationItemBack{
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)searchClick:(id)sender {
    if (self.searchTF.text.length == 0) {
        [SVProgressHUD showImage:NULL_IMAGE status:@"请输入搜索内容~"];
        return;
    }
    [self request:self.searchTF.text];
    
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArr.count;
}


- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CDSoftwareCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"kCDSoftwareCellID" forIndexPath:indexPath];
    NSDictionary *dic = self.dataArr[indexPath.row];
    cell.dic = dic;
    return cell;
}

#pragma mark - UICollectionViewDelegateLeftAlignedLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake((kDeviceWidth - 18*4 -20)/5, (kDeviceWidth - 18*4 -20)/5+45);
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.dataArr[indexPath.row];
    !self.softClickBlock ?:self.softClickBlock(dic);
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)getDate{
    NSString *file = [[NSBundle mainBundle] pathForResource:@"HotSoftware" ofType:@"plist"];
    NSMutableDictionary*dataDic = [[NSMutableDictionary alloc]initWithContentsOfFile:file];
    NSLog(@"%@",dataDic);
    self.dataArr = [NSMutableArray arrayWithArray:dataDic[@"hotApp"]];
    [self.collectionView reloadData];


}

-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    return _dataArr;
}
#pragma mark - 网络请求
-(void)request:(NSString *)str{
    [SVProgressHUD show];
    
    NSString *urlstr=[NSString stringWithFormat:@"http://itunes.apple.com/search?term=%@&entity=software&country=CN",str];
    urlstr = [urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"#%^{}\"[]|\\<> "].invertedSet];
    NSURL*url=[NSURL URLWithString:urlstr];
    //初始化一个可变请求
    NSMutableURLRequest*requset=[NSMutableURLRequest requestWithURL:url];
    //设置超时时间
    requset.timeoutInterval=5;

    [requset setCachePolicy:NSURLRequestReturnCacheDataElseLoad];

    requset.HTTPMethod=@"POST";

    NSURLSession*session=[NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:requset completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        [SVProgressHUD dismiss];
        if (error==nil) {

            //获取相应信息
            NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",content);

            @try {
                //解析json
                
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                    NSLog(@"%@",dic);
                NSArray *results = dic[@"results"];
                self.dataArr = [[NSMutableArray alloc]init];
                for (NSDictionary *dic in results) {
                    NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
                    d[@"artworkUrl60"] = dic[@"artworkUrl60"];
                    d[@"bundleId"] = dic[@"bundleId"];
                    d[@"trackName"] = dic[@"trackName"];
                    [self.dataArr addObject:d];
                }
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [self.collectionView reloadData];
                }];
                
                
            } @catch (NSException *exception) {
                NSLog(@"解析错误00");
            } @finally {
                
            }
                
        }else{

            NSLog(@"加载失败请重新尝试");
        }
    }];
    
    [dataTask resume];
}
@end
